# -*- coding:utf-8 -*-
import base64
import json
import uuid

from util.redis_connect import RedisPoolConnect
from util.response_format import ResponseFormat
# 缓存连接池
REDIS_POOL_EMAIL = RedisPoolConnect(0)
REDIS_POOL_PHONE = RedisPoolConnect(1)
REDIS_POOL_TOKEN = RedisPoolConnect(2)
EMAIL = "email"
PHONE = "phone"

VERIFY_TYPE_MAPPING = {
    EMAIL: REDIS_POOL_EMAIL,
    PHONE: REDIS_POOL_PHONE,
}


def handler(event, context):
    logger = context.getLogger()
    params = json.loads(base64.b64decode(event["body"]).decode().replace("'", '"'))
    user_name = params.get("userName", None)
    verify_id = params.get("verifyId", None)
    verify_type = params.get("verifyType", None)
    verification_code = params.get("verificationCode", None)
    key = f"{verify_id}+{user_name}"
    verify_type_redis = VERIFY_TYPE_MAPPING.get(verify_type)
    if verify_type_redis.find_key_value(key) == verification_code:
        logger.info("验证成功")
        user_token = str(uuid.uuid4())
        REDIS_POOL_TOKEN.set_key_value(user_token, user_name, 4 * 60 * 60)
        return ResponseFormat({"code": 200, "msg": "验证码正确", "auth_token": user_token}, 200).to_json()
    logger.info("验证失败")
    return ResponseFormat({"code": 200, "msg": "验证码错误"}, 200, ).to_json()
